package com.auto.printer.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.auto.printer.common.exception.MyException;
import com.google.common.collect.Lists;
import lombok.Data;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTOleItem;

import java.util.ArrayList;
import java.util.List;

/**
 * 页码处理
 *
 * @author LoveHuaHua
 * @date 2023年07月14日 20:15
 * @description believe in yourself
 */
public class PDFPageUtil {

    /**
     * 1-12,13,15
     * @param pageStr
     * @return
     */
    public static List<Integer> generatePageList(String pageStr) {
        ArrayList<Integer> res = Lists.newArrayList();
        String[] split = pageStr.split(",");
        for (String string : split) {
            String[] strings = string.split("-");
            if (strings.length == 1) {
                //一页
                res.add(NumberUtil.parseInt(strings[0]));
            } else if (strings.length == 2) {
                //多页
                int start = NumberUtil.parseInt(strings[0]);
                int end = NumberUtil.parseInt(strings[1]);
                for (int i = start; i < end; i++) {
                    res.add(i);
                }
            } else {
                throw new MyException("请检查页码格式");
            }
        }

        return res;
    }

    public static void executePdf(String pageStr,PDDocument load){
        //总页码
        int numberOfPages = load.getNumberOfPages();
        if (StrUtil.isBlankOrUndefined(pageStr)){
            return;
        }
        List<Integer> integers = PDFPageUtil.generatePageList(pageStr);
        for (int i = 1; i <= numberOfPages ; i++) {
            //换算之后的页码
            int page = i - 1;
            if (!integers.contains(page)) {
                load.removePage(page);
            }
        }
    }
}
